package io.wdb.modules.generator.generator.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.wdb.common.annotation.SysLog;
import io.wdb.handler.WechatMessageHandler;
import io.wdb.modules.generator.generator.entity.BookgridInfoEntity;
import io.wdb.modules.generator.generator.entity.customer.BookEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.ProcessInstructionLogCustomer;
import io.wdb.modules.generator.generator.entity.statistics.BookCheckAllRes;
import io.wdb.modules.generator.generator.entity.statistics.BookCheckOneRes;
import io.wdb.modules.generator.generator.entity.statistics.BookGridAvailableRes;
import io.wdb.modules.generator.generator.entity.statistics.LampStrategyRes;
import io.wdb.modules.generator.generator.entity.web.BaseResponse;
import io.wdb.modules.generator.generator.entity.web.BookShelfLoRes;
import io.wdb.modules.generator.generator.entity.web.BookShelfOperation;
import io.wdb.modules.generator.generator.entity.web.DaysQueryRequest;
import io.wdb.modules.generator.generator.entity.web.OperationResponse;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.StatisticsDetailResponse;
import io.wdb.modules.generator.generator.entity.web.UserOperationCurveResponse;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.BookgridInfoService;
import io.wdb.modules.generator.generator.service.operation.BookShelfOperationAppsService;
import io.wdb.modules.generator.generator.service.operation.BookShelfOperationService;
import io.wdb.modules.manager.sys.entity.SysUserEntity;
import io.wdb.modules.manager.sys.service.SysUserService;

@RestController
@RequestMapping("operation")
public class BookShelfOperationAppsController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(BookShelfOperationAppsController.class);
	
	@Autowired
	private BookShelfOperationService bookShelfOperationService;
	
	@Autowired
	private BookShelfOperationAppsService bookShelfOperationAppsService;
	
	@Autowired
	private BookgridInfoService bookgridInfoService;
	
	/**
	 * 
	 * @Method:getBookGrids
	 * @Description:根据书柜编号获取各个书格柜门打开状态
	 * @Time 2018年3月8日 下午4:57:05
	 * @author: Tom
	 * @param bookshelfInfoEntity
	 * @return
	 */
	@RequestMapping("/bookgrids")
	public BaseResponse getBookGrids(BookShelfOperation bookShelfOperation){
		BaseResponse baseResponse = success();
		try {
			List<BookgridInfoEntity> bookgridInfoEntities = bookShelfOperationService.getBookGridsByShelfCode(bookShelfOperation.getBookShelfCode());
			List<OperationResponse> operationResponses = new ArrayList<>();
			for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntities) {
				int lockStatus = bookgridInfoEntity.getLockStatus();
				String lockStatusStr = "";
				OperationResponse operationResponse = new OperationResponse();
				operationResponse.setKey(bookgridInfoEntity.getBookgridCode());
				if(lockStatus==5) {//正常已关闭
					lockStatusStr = "0";
					operationResponse.setValue("0");
				}else if(lockStatus==1) {//正常已打开
					lockStatusStr = "1";
					operationResponse.setValue("1");
				}else {
					lockStatusStr = "2";//状态异常
					operationResponse.setValue("0");
				}
				operationResponses.add(operationResponse);
			} 
			baseResponse.setDetail(operationResponses);
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		} 
		return baseResponse;
	}
	/**
	 * 
	 * @Method:bookShelfCurrentCondition
	 * @Description:书柜当前状态结果
	 * @Time 2018年3月1日 下午4:46:49
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/bookShelfCurrentCondition")
	//@RequiresPermissions("operationApps:bookShelfCurrentCondition")
	public BaseResponse bookShelfCurrentCondition(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		if(daysQueryRequest.getBookShelfCode()==null||"".equals(daysQueryRequest.getBookShelfCode().trim())) {
			WebResponse response = new WebResponse();
			response.setCode(ResponseEnum.SHELF_CODE_IS_NULL.getCode());
			response.setMessage("请先选定某个书柜");
			baseResponse.setDetail(response);
			return baseResponse;
		}
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		List<OperationResponse> operationResponses = bookShelfOperationService.bookShelfCurrentCondition(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		baseResponse.setDetail(detailResponse);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:refreshGridOne
	 * @Description:单书格盘点
	 * @Time 2018年3月8日 下午6:15:53
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/refreshGridOne")
	@RequiresPermissions("operation:bookshelf:refreshone")
	@SysLog("app端单书格盘点")
	public BaseResponse refreshGridOne(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		try {
			WebResponse webResponse = bookShelfOperationService.checkBookGridOne(bookShelfOperation.getBookGridCode());
			if(webResponse.getCode()==100) {//盘点成功
				BookCheckOneRes bookCheckRes = JSON.parseObject(webResponse.getMessage(), BookCheckOneRes.class);
				//当前在柜书籍数
				List<BookEntityCustomer> bookEntityEntities = new ArrayList<BookEntityCustomer>();
				if(bookCheckRes.getData()!=null&&bookCheckRes.getData().size()>0) {
					bookEntityEntities = bookShelfOperationAppsService.getBookInfosByRfids(bookCheckRes.getData());
				}
				List<UserOperationCurveResponse> curveResponses = new ArrayList<UserOperationCurveResponse>();
				for(BookEntityCustomer bookEntityCustomer:bookEntityEntities) {
					List<OperationResponse> operationResponses = new ArrayList<>();
					OperationResponse rfidResponse = new OperationResponse();
					rfidResponse.setKey("RFID");
					rfidResponse.setValue(bookEntityCustomer.getRfidCode());
					operationResponses.add(rfidResponse);
					
					OperationResponse isbnResponse = new OperationResponse();
					isbnResponse.setKey("ISBN");
					isbnResponse.setValue(bookEntityCustomer.getIsbnNo());
					operationResponses.add(isbnResponse);
					
					OperationResponse bookNameResponse = new OperationResponse();
					bookNameResponse.setKey("书籍名称");
					bookNameResponse.setValue(bookEntityCustomer.getBookName());
					operationResponses.add(bookNameResponse);
					
					UserOperationCurveResponse curveResponse = new UserOperationCurveResponse();
					curveResponse.setDateStr("");
					curveResponse.setOperationResponses(operationResponses);
					curveResponses.add(curveResponse);
				}
				baseResponse.setItems(curveResponses);
				baseResponse.setDetail(webResponse);
			}else {//盘点失败
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:refreshGridAll
	 * @Description:整柜盘点
	 * @Time 2018年3月8日 下午6:16:45
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/refreshGridAll")
	@RequiresPermissions("operation:bookshelf:refreshall")
	@SysLog("app端整柜盘点")
	public BaseResponse refreshGridAll(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		try {
			WebResponse webResponse = bookShelfOperationService.checkBookGridAll(bookShelfOperation.getBookShelfCode());
			if (webResponse.getCode() == 100) {// 盘点成功
				BookCheckAllRes bookCheckAllRes = JSON.parseObject(webResponse.getMessage(), BookCheckAllRes.class);
				//根据查到的rfid获取Isbn和书籍名称
				// 当前在柜书籍数
				List<UserOperationCurveResponse> curveResponses = new ArrayList<UserOperationCurveResponse>();
				for (int i = 0; i < 8; i++) {
					System.out.println(bookCheckAllRes.getData().get(i).get(bookShelfOperation.getBookShelfCode()+"0"+(i+1)));
					List<String> rfids = bookCheckAllRes.getData().get(i).get(bookShelfOperation.getBookShelfCode()+"0"+(i+1));
					if(rfids==null||rfids.size()<1) {
						continue;
					}
					List<BookEntityCustomer> bookEntityEntities = bookShelfOperationAppsService.getBookInfosByRfids(bookCheckAllRes.getData().get(i).get(bookShelfOperation.getBookShelfCode()+"0"+(i+1)));
					for (BookEntityCustomer bookEntityCustomer : bookEntityEntities) {
						List<OperationResponse> operationResponses = new ArrayList<>();
						OperationResponse rfidResponse = new OperationResponse();
						rfidResponse.setKey("RFID");
						rfidResponse.setValue(bookEntityCustomer.getRfidCode());
						operationResponses.add(rfidResponse);
						
						OperationResponse isbnResponse = new OperationResponse();
						isbnResponse.setKey("ISBN");
						isbnResponse.setValue(bookEntityCustomer.getIsbnNo());
						operationResponses.add(isbnResponse);
						
						OperationResponse bookNameResponse = new OperationResponse();
						bookNameResponse.setKey("bookName");
						bookNameResponse.setValue(bookEntityCustomer.getBookName());
						operationResponses.add(bookNameResponse);
						
						OperationResponse bookGridResponse = new OperationResponse();
						bookGridResponse.setKey("bookGridCode");
						bookGridResponse.setValue(bookEntityCustomer.getCurrentGridCode().substring(11));
						operationResponses.add(bookGridResponse);
						
						UserOperationCurveResponse curveResponse = new UserOperationCurveResponse();
						curveResponse.setDateStr("");
						curveResponse.setOperationResponses(operationResponses);
						curveResponses.add(curveResponse);
					}
				}
				baseResponse.setItems(curveResponses);
				baseResponse.setDetail(webResponse);
			} else {
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:unlockBookGrid
	 * @Description:用户开关柜
	 * @Time 2018年3月8日 下午6:32:42
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/unlock")
	@RequiresPermissions("operation:bookshelf:unlockone")
	@SysLog("app端用户开关柜")
	public BaseResponse unlockBookGrid(BookShelfOperation bookShelfOperation){
		BaseResponse baseResponse = success();
		try {
			WebResponse webResponse = bookShelfOperationService.unlock(bookShelfOperation.getBookGridCode());
			if(webResponse.getCode()==100) {
				baseResponse.setDetail(webResponse);
			}else {
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	
	/**
	 * 
	 * @Method:restartBookShelf
	 * @Description:用户重启书柜
	 * @Time 2018年2月23日 下午3:08:48
	 * @author: Tom
	 * @param bookgridInfoEntity
	 * @return
	 */
	@RequestMapping("/restart")
	@RequiresPermissions("operation:bookshelf:restartone")
	@SysLog("app端用户重启书柜")
	public BaseResponse restartBookShelf(BookShelfOperation bookShelfOperation){
		BaseResponse baseResponse = success();
		try {
			WebResponse webResponse = bookShelfOperationService.restart(bookShelfOperation.getBookShelfCode());
			if(webResponse.getCode()==100) {
				baseResponse.setDetail(webResponse);
			}else {
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:availableBookGrid
	 * @Description:书格可用不可用
	 * @Time 2018年3月8日 下午6:35:09
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/maintain")
	@RequiresPermissions("operation:bookshelf:maintaininter")
	@SysLog("书格可用不可用设置")
	public BaseResponse maintainBookGrid(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		WebResponse webResponse = new WebResponse();
		if(bookShelfOperation.getBookGridCode()==null||bookShelfOperation.getBookGridCode().equals("")) {
			baseResponse.setResult(0);
			baseResponse.setCode(2000);
			baseResponse.setMessage("书格编号不能为空");
			return baseResponse;
		}
		try {
			webResponse = bookgridInfoService.updateAvailable(bookShelfOperation);
			if(webResponse.getCode()==100) {
				baseResponse.setDetail(webResponse);
			}else {
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) { 
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:getGridAvailableStatus
	 * @Description:获得书柜各个书格是否可用，以及详细信息
	 * @Time 2018年3月15日 下午3:19:18
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/maintaindetail")
	@RequiresPermissions("operation:bookshelf:maintaindetail")
	public BaseResponse maintaindetail(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		if(bookShelfOperation.getBookShelfCode()==null||bookShelfOperation.getBookShelfCode().equals("")) {
			baseResponse.setResult(0);
			baseResponse.setCode(2000);
			baseResponse.setMessage("书柜编号不能为空");
			return baseResponse;
		}
		try { 
			List<BookGridAvailableRes> entities  = bookgridInfoService.getGridAvailableDetail(bookShelfOperation);
			baseResponse.setItems(entities);
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:lampStrategy
	 * @Description:灯光策略
	 * @Time 2018年3月16日 下午2:32:05
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/lampStrategy")
	@RequiresPermissions("operation:bookshelf:lampstaragy")
	@SysLog("灯光策略设置")
	public BaseResponse lampStrategy(BookShelfOperation bookShelfOperation) {
		String json = JSONObject.toJSONString(bookShelfOperation);
		logger.info("灯光策略客户端传递来的数据为:\t"+json);
		BaseResponse baseResponse = success();
		
		try {
			WebResponse webResponse = bookShelfOperationService.lampStrategy(bookShelfOperation);
			if(webResponse.getCode()==100) {
				baseResponse.setDetail(webResponse);
			}else {
				baseResponse.setResult(0);
				baseResponse.setCode(webResponse.getCode());
				baseResponse.setMessage(webResponse.getMessage());
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:lampCurrentStrategy
	 * @Description:书柜当前灯光策略
	 * @Time 2018年3月16日 下午5:06:48
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/lampCurrentStrategy")
	@RequiresPermissions("operation:bookshelf:lampcurrentstaragy")
	public BaseResponse lampCurrentStrategy(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		try {
			LampStrategyRes lampStrategyRes = bookShelfOperationService.lampStrategyCurrent(bookShelfOperation);
			baseResponse.setDetail(lampStrategyRes);
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:lampCurrentStrategy
	 * @Description:机柜日志
	 * @Time 2018年3月16日 下午5:06:48
	 * @author: Tom
	 * @param bookShelfOperation
	 * @return
	 */
	@RequestMapping("/bookShelfLogs")
	//@RequiresPermissions("operation:bookshelf:loginter")
	public BaseResponse bookShelfLogs(BookShelfOperation bookShelfOperation) {
		BaseResponse baseResponse = success();
		try {
			List<BookShelfLoRes> customers = bookShelfOperationService.bookShelfLogs(bookShelfOperation);
			baseResponse.setItems(customers);
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	@RequestMapping("/getInfoByNickName")
	public BaseResponse getInfoByNickName(String nickname) {
		BaseResponse baseResponse = success();
		try {
			List<SysUserEntity> entities = wechatMessageHandler.getUsersByNickname(nickname);
			baseResponse.setItems(entities);
		} catch (IOException e) {
			baseResponse = failed(e);
			e.printStackTrace();
		}
		return baseResponse;
	}
	@Autowired
	private SysUserService sysUserService;
	@RequestMapping("/bindWx")
	public BaseResponse bindWx(SysUserEntity entity) {
		BaseResponse baseResponse = success();
		sysUserService.update(entity);
		return baseResponse;
	}
	@Autowired
	private WechatMessageHandler wechatMessageHandler;
	
	@RequestMapping("/test")
	public BaseResponse testOne() {
		BaseResponse baseResponse = success();
		try {
			wechatMessageHandler.getUserList();
		} catch (IOException e) {
			baseResponse = failed(e);
			e.printStackTrace();
		}
		return baseResponse;
	}
}
